<?php
class ModelCommunityUser extends Model{
    public function addUser($data,$server,$avatarPath){
        $this->db->query("INSERT INTO " . DB_PREFIX . "community_users SET user_ip='" . $this->db->escape($server['REMOTE_ADDR']) . "',  customer_id='" . (int)$this->session->data['cart_customer_id'] . "', user_regdate='" . time() . "', username='" . $this->db->escape($data['forumusername']) . "', user_email='" . $this->db->escape($data['email']) . "', user_lastvisit='" . time() . "', user_avatar='" . $this->db->escape($avatarPath) . "', user_actkey='" . $this->db->escape($data['actkey']) . "'");

        $uid=$this->db->getLastId();

        $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value`=`value`+1 WHERE `key`='total_users'");
        $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value`='" . $this->db->escape(serialize(array($uid,$this->db->escape($data['forumusername'])))) . "' WHERE `key`='newest_member'");

        unset($this->session->data['cart_customer_id']);
    }

    public function getTotalUsersByForumUserName($forumUserName){
        $query=$this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "community_users WHERE username='" . $forumUserName . "'");
        return $query->row['total'];
    }

    public function getPermission($getData,$userType,$userRank){
        $sql="SELECT p.*, r.*";

        if($userType==3){
            $sql.=", f.forum_mod_ids";
        }

        $sql.=" FROM " . DB_PREFIX . "community_permission AS p LEFT JOIN " . DB_PREFIX . "community_role AS r ON (r.role_id=p.role_id AND";

        if($userType!=5){
            $sql.=" r.rank_id='0')";
        }else{
           $sql.=" r.rank_id='" . (int)$this->customer->getForumUserRank() . "')";
        }

        if($userType==3){
            $sql.=" LEFT JOIN " . DB_PREFIX . "community_forum AS f ON (f.forum_id='" . (int)$getData['fid'] . "')";
        }

        /*if(!($userType==5 || $userType==3)){
            $sql.=" WHERE p.forum_id='0'";
        }else{
            $sql.=" WHERE p.forum_id='" . (int)$getData['fid'] . "'";
        }*/

        $sql.=" WHERE p.forum_id='" . (int)$getData['fid'] . "' AND p.role_id='" . (int)$userType . "'";

        if($userType!=5){
            $sql.=" AND p.rank_id='0'";
        }else{
            $sql.=" AND p.rank_id='" . (int)$userRank . "'";
        }

        $sql.=" LIMIT 0,1";

        $query=$this->db->query($sql);

        return $query->row;
    }
}
?>